package com.ita.shoppingcart.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ita.shoppingcart.bean.Goods;
import com.ita.shoppingcart.bean.User;
import com.ita.shoppingcart.cart.CartManager;
import com.ita.shoppingcart.cart.CartManagerImpl;

/**
 * Servlet implementation class PushToCartServlet
 */
public class PushToCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CartManager cartManager = new CartManagerImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PushToCartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int id = Integer.parseInt(request.getParameter("id"));
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if(user != null){
			Map<Integer, Goods> cart = (Map<Integer, Goods>) session.getAttribute("Cart");
			if(cart == null){
				cart = new HashMap<Integer, Goods>();
				session.setAttribute("cart", cart);
			}
			session.setAttribute("cart", cartManager.pushToCart(id, cart));
			response.sendRedirect("./listCart");
		}else {
			response.sendRedirect("./index");
		}
//		request.getRequestDispatcher("./listCart").forward(request, response);
	}

}
